package tq.com.tqstudent.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lib.common.base.BaseActivity;
import com.lib.common.utils.AppUtil;
import com.lib.common.utils.LogUtil;
import com.lib.common.utils.SPUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tencent.connect.auth.QQToken;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import tq.com.tqstudent.App;
import tq.com.tqstudent.Constants;
import tq.com.tqstudent.R;
import tq.com.tqstudent.bean.ThirdPartyLoginBean;
import tq.com.tqstudent.bean.UserBean;
import tq.com.tqstudent.bean.UserInfo;
import tq.com.tqstudent.bean.params.LoginParams;
import tq.com.tqstudent.net.ok.StringDialogCallback;
import tq.com.tqstudent.widgets.ClearEditText;

/**
 * @Author rames
 * @date 2019/2/27 14:40
 */
public class LoginActivity extends BaseActivity {
    @BindView(R.id.phone_edit)
    ClearEditText phoneEdit;
    @BindView(R.id.pwd_edit)
    EditText pwdEdit;
    private String nameCache = ""; // 缓存用户名
    private final static String NAME_CACHE = "NAME_CACHE";
    public static Tencent mTencent;

    public static void show(Activity activity) {
        activity.startActivity(new Intent(activity, LoginActivity.class));
    }

    @Override
    public int initLayout() {
        return R.layout.activity_login;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        setTitle("登录");
        mTencent = Tencent.createInstance(Constants.QQ_APP_ID, getApplicationContext());
        nameCache = SPUtils.getInstance(this).getString(NAME_CACHE, "");
        phoneEdit.setText(nameCache);
        phoneEdit.setSelection(nameCache.length());
        getTitleView().getBackImg().setVisibility(View.INVISIBLE);
    }

    @Override
    public void initData() {

    }

    @OnClick({R.id.forget_tv, R.id.register_tv, R.id.login_tv, R.id.un_login_tv, R.id.qq_iv, R.id.wx_iv})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.forget_tv:
                RegisterActivity.show(this, RegisterActivity.PWD_TYPE.MODIFY_PWD);
                break;
            case R.id.register_tv:
                RegisterActivity.show(this, RegisterActivity.PWD_TYPE.REGISTER);
                break;
            case R.id.login_tv:
                login();
                break;
            case R.id.un_login_tv:
                HomeActivity.show(this);
                LoginActivity.this.finish();
                break;
            case R.id.qq_iv:
                qqLogin();
                break;
            case R.id.wx_iv:
                wxLogin();
//                LogUtil.e(FileUtil.deleteFolderFile(Constants.DOWNLOAD_PDF_URL, false) ? "删除成功" : "删除失败");
                break;
        }
    }

    /** 密码登录 */
    private void login() {
        String name = phoneEdit.getText().toString().trim();
        String pwd = pwdEdit.getText().toString().trim();
        if(name.length() < 1){
            showToast("请输入用户名");
            return;
        }

        if(pwd.length() < 1){
            showToast("请输入密码");
            return;
        }
        LoginParams params = new LoginParams();
        params.name = name;
        params.pwd = pwd;
        params.pic = "";
        String parStr = new Gson().toJson(params);

        loginTask(parStr);
    }

    @Subscribe
    public void wxLoginEvent(ThirdPartyLoginBean event){
        showToast("微信登录成功");
        // 第三方,微信登录
        LoginParams params = new LoginParams();
        params.name = event.openid;
        params.dis_name = event.nickname;
        params.channel = 1;
        params.pwd = "";
        params.pic = event.headimgurl;
        String parStr = new Gson().toJson(params);

        loginTask(parStr);
    }

    private void loginTask(String json){
        OkGo.<String>post(App.getHttpUrl("api/user/session"))
                .tag(this)
                .upJson(json)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try{
                            JSONObject result = new JSONObject(response.body());
                            if(result.getInt("ret") == 0){
                                UserBean info = new Gson().fromJson(result.getString("profile"), UserBean.class);
                                String token = result.getString("tk");
                                if(null != info){
                                    if(!TextUtils.isEmpty(info.phone)) {
                                        SPUtils.getInstance(LoginActivity.this).putString(NAME_CACHE, info.phone);
                                    }
                                    showToast("登录成功");
                                    UserInfo.set(info, token);
                                    HomeActivity.show(LoginActivity.this);
                                    LoginActivity.this.finish();
                                }
                            } else {
                                String msg = result.getString("msg");
                                showToast(TextUtils.isEmpty(msg) ? "登录失败" : msg);
                            }
                        }catch (Exception e){
                            showToast("登录失败");
                            e.printStackTrace();
                        }
                    }
                });
    }

    // 微信授权登录
    private void wxLogin(){
        //先判断是否安装微信APP,按照微信的说法，目前移动应用上微信登录只提供原生的登录方式，需要用户安装微信客户端才能配合使用。
        if (!AppUtil.isInstalled(this, Constants.WX_PACKAGE_NAME)) {
            showToast("您还未安装微信客户端");
            return;
        }

        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "diandi_wx_login";
        //像微信发送请求
        App.getWxApi().sendReq(req);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mTencent.onActivityResultData(requestCode, resultCode, data, loginListener);

        if(requestCode == com.tencent.connect.common.Constants.REQUEST_API){
            if (resultCode == com.tencent.connect.common.Constants.REQUEST_LOGIN) {
                Tencent.handleResultData(data, loginListener);
            }
        }
    }

    // QQ授权登录
    private void qqLogin(){
        if (mTencent.isSupportSSOLogin(this)) {
            if (mTencent.isSessionValid())
                mTencent.logout(this);
            mTencent.login(this, "all", loginListener);
        } else{
            showToast("您还未安装QQ客户端");
        }
    }

    /**
     * 登陆监听
     */
    IUiListener loginListener = new IUiListener() {

        @Override
        public void onComplete(Object o) {
            LogUtil.e("loginListener onComplete: " + o.toString());

            try{
                JSONObject obj = (JSONObject) o;
                String openID = obj.getString("openid");
                String accessToken = obj.getString("access_token");
                String expires = obj.getString("expires_in");
                mTencent.setOpenId(openID);
                mTencent.setAccessToken(accessToken,expires);
                QQToken qqToken = mTencent.getQQToken();
                com.tencent.connect.UserInfo info = new com.tencent.connect.UserInfo(LoginActivity.this, qqToken);
                info.getUserInfo(new IUiListener() {
                    @Override
                    public void onComplete(Object o) {
                        // 头像字段:figureurl_qq, nickname
                        LogUtil.e("IUiListener onComplete: " + o.toString());
                        try{
                            JSONObject obj = (JSONObject) o;

                            LoginParams params = new LoginParams();
                            params.name = openID;
                            params.dis_name = obj.getString("nickname");
                            params.channel = 1;
                            params.pwd = "";
                            params.pic = obj.getString("figureurl_qq");

                            Gson gson = new GsonBuilder().disableHtmlEscaping().create();
                            String parStr = gson.toJson(params);
                            LogUtil.e("parStr: "+parStr);
                            loginTask(parStr);
                        } catch (Exception e){
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(UiError uiError) {

                    }

                    @Override
                    public void onCancel() {

                    }
                });
            } catch (Exception e){
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError uiError) {
            LogUtil.e("loginListener error: "+uiError.errorDetail);
        }

        @Override
        public void onCancel() {
            LogUtil.e("loginListener cancel: ");
        }
    };
}
